<template>
	<div class="dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" :close-on-click-modal="false" width="1200px">
			<el-form
				v-loading="state.dialog.loading"
				ref="formRef"
				:model="state.ruleForm"
				:rules="state.rules"
				:disabled="state.dialog.type === 'view' ? true : false"
			>
				<el-tabs v-model="state.ruleForm.tabs_type">
					<el-tab-pane label="基本信息" :name="1">
						<el-row class="mb20" :gutter="20">
							<el-col :span="12">
								<el-form-item label="商品名称" prop="title">
									<el-input v-model="state.ruleForm.title" @blur="onSetGoodsInfo" placeholder="请输入商品名称" clearable />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="商品分类" prop="goods_class_id">
									<el-select
										v-model="state.ruleForm.goods_class_id"
										clearable
										placeholder="请输入关键字/选择商品分类"
										filterable
										remote
										:remote-method="goodsClassIdRemoteMethod"
										remote-show-suffix
										:loading="state.goodsClassIdSelect.loading"
										@focus="onGoodsClassIdFocus"
										@blur="onSetGoodsInfo"
									>
										<el-option v-for="item in state.goodsClassIdSelect.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row class="mb20" :gutter="20">
							<el-col :span="12">
								<el-form-item label="商品品牌" prop="brand_id">
									<el-select
										v-model="state.ruleForm.brand_id"
										clearable
										placeholder="请输入关键字/选择商品品牌"
										filterable
										remote
										:remote-method="brandIdRemoteMethod"
										remote-show-suffix
										:loading="state.brandIdSelect.loading"
										@focus="onBrandIdFocus"
										@blur="onSetGoodsInfo"
									>
										<el-option v-for="item in state.brandIdSelect.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="关联供应商" prop="supplier_id">
									<el-select
										v-model="state.ruleForm.supplier_id"
										clearable
										placeholder="请输入关键字/选择供应商"
										filterable
										remote
										:remote-method="supplierIdRemoteMethod"
										remote-show-suffix
										:loading="state.supplierIdSelect.loading"
										@focus="onSupplierIdFocus"
										@change="onSupplierIdChange"
										@blur="onSetGoodsInfo"
									>
										<el-option v-for="item in state.supplierIdSelect.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row class="mb20" :gutter="20">
							<el-col :span="12">
								<el-form-item label="商品种类" prop="type">
									<el-radio-group v-model="state.ruleForm.type" @change="onSetGoodsInfo">
										<el-radio :value="1">普通商品</el-radio>
										<el-radio :value="2">礼包商品</el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item v-if="state.ruleForm.type === 2" label="礼包等级" prop="grade">
									<el-select v-model="state.ruleForm.grade" @blur="onSetGoodsInfo" clearable placeholder="请选择礼包等级">
										<el-option v-for="item in state.gradeOptions" :key="item.value" :label="item.label" :value="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="商品描述" prop="descri">
									<el-input
										v-model="state.ruleForm.descri"
										@blur="onSetGoodsInfo"
										type="textarea"
										:autosize="{ minRows: 4, maxRows: 4 }"
										placeholder="请输入商品描述"
										clearable
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col v-if="state.dialog.type === 'edit'" :span="12">
								<el-form-item label="虚拟销量" prop="virtual_sales">
									<el-input
										v-model="state.ruleForm.virtual_sales"
										@blur="onSetGoodsInfo"
										placeholder="请输入虚拟销量"
										clearable
										disabled
										class="mr5 w87"
									/>
									<el-button type="primary" @click="onEditVirtualSales"> 修改 </el-button>
								</el-form-item>
							</el-col>
							<el-col v-else :span="12">
								<el-form-item label="虚拟销量" prop="virtual_sales">
									<el-input
										v-model="state.ruleForm.virtual_sales"
										placeholder="请输入虚拟销量"
										clearable
										@input="onVerifiyNumberIntegerVirtualSales"
										@blur="onSetGoodsInfo"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="排序" prop="display_order">
									<el-input
										v-model="state.ruleForm.display_order"
										@blur="onSetGoodsInfo"
										placeholder="请输入排序"
										clearable
										@input="onVerifiyNumberIntegerDisplayOrder"
									/>
								</el-form-item>
							</el-col>
						</el-row>
					</el-tab-pane>
					<el-tab-pane label="图片信息" :name="2">
						<el-row class="mb20" :gutter="20">
							<el-col :span="12">
								<el-form-item label="商品主图" prop="thumb">
									<ImageUploadCOS
										v-model="state.ruleForm.thumb"
										image-size="750*750"
										path="goods/thumb"
										:is-dialog-upload="state.dialog.isShowDialog"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="商品视频" prop="thumb_video">
									<ImageUploadCOS
										v-model="state.ruleForm.thumb_video"
										:file-size="50"
										:file-type="['mp4', '3gp', 'mov', 'm4v']"
										path="goods/video"
										:is-dialog-upload="state.dialog.isShowDialog"
										:is-delete="state.dialog.type === 'view' ? true : false"
										video
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row class="mb20" :gutter="20">
							<el-col :span="24">
								<el-form-item label="商品轮播图" prop="images">
									<ImageUploadDraggableCOS
										v-model="state.ruleForm.images"
										:is-delete="state.dialog.type === 'view' ? true : false"
										image-size="800*800，可拖拽改变图片顺序"
										:limit="4"
										path="goods/images"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="商品详情图" prop="details">
									<ImageUploadDraggableCOS
										v-model="state.ruleForm.details"
										:is-delete="state.dialog.type === 'view' ? true : false"
										image-size="宽750，高1000以内，可拖拽改变图片顺序"
										path="goods/details"
									/>
								</el-form-item>
							</el-col>
						</el-row>
					</el-tab-pane>
					<el-tab-pane label="规格库存" :name="3">
						<el-row class="mb20" :gutter="20">
							<el-col :span="12">
								<el-form-item label="商品规格" prop="is_specs">
									<el-radio-group v-model="state.ruleForm.is_specs" @change="onSetGoodsInfo">
										<el-radio-button :value="1">单规格</el-radio-button>
										<el-radio-button :value="2">多规格</el-radio-button>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="批量设置佣金" prop="is_batch_setting">
									<el-radio-group v-model="state.ruleForm.is_batch_setting">
										<el-radio :value="1">是</el-radio>
										<el-radio :value="0">否</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row v-if="state.ruleForm.is_specs === 1" class="mb20" :gutter="20">
							<el-col :span="24">
								<el-form-item label="规格属性">
									<el-table :data="state.specifications_val" border>
										<el-table-column v-if="state.dialog.type === 'view'" label="规格ID" align="center" prop="id" />
										<el-table-column label="图片" align="center" prop="icon">
											<template #default="{ row }">
												<ImageUploadCOS v-model="row.icon" :isShowTip="false" path="goods/skuThumb" class="icon-imageUploadCOS" />
											</template>
										</el-table-column>
										<el-table-column label="规格名称" align="center" prop="k">
											<template #default="{ row }">
												<el-input v-model="row.skus[0].k" @blur="onSetGoodsInfo" placeholder="规格名称" />
											</template>
										</el-table-column>
										<el-table-column label="规格值" align="center" prop="v">
											<template #default="{ row }">
												<el-input v-model="row.skus[0].v" @blur="onSetGoodsInfo" placeholder="规格值" />
											</template>
										</el-table-column>
										<el-table-column label="原价" align="center" prop="original_price">
											<template #default="{ row }">
												<el-input
													v-model="row.original_price"
													placeholder="原价"
													@input="(val: string) => onVerifiyNumberIntegerOriginalPrice(val, row)"
													@blur="onSetGoodsInfo"
												/>
											</template>
										</el-table-column>
										<el-table-column label="成本价" align="center" prop="cost_price">
											<template #default="{ row }">
												<el-input
													v-model="row.cost_price"
													placeholder="成本价"
													@input="(val: string) => onVerifiyNumberIntegerCostPrice(val, row)"
													@blur="onSetGoodsInfo"
												/>
											</template>
										</el-table-column>
										<el-table-column label="平台服务费" align="center" prop="service_price">
											<template #default="{ row, $index }">
												<el-input
													v-model="row.service_price"
													placeholder="平台服务费"
													@input="(val: string) => onVerifiyNumberIntegerServicePrice(val, row)"
													@blur="onServicePriceBlur(row, $index)"
												/>
											</template>
										</el-table-column>
										<el-table-column label="铜牌佣金" align="center" prop="bronze_commission">
											<template #default="{ row }">
												<el-input
													v-model="row.bronze_commission"
													placeholder="铜牌佣金"
													@input="(val: string) => onVerifiyNumberIntegerBronzeCommission(val, row)"
													@blur="onSetGoodsInfo"
												/>
											</template>
										</el-table-column>
										<el-table-column label="银牌佣金" align="center" prop="silver_commission">
											<template #default="{ row }">
												<el-input
													v-model="row.silver_commission"
													placeholder="银牌佣金"
													@input="(val: string) => onVerifiyNumberIntegerSilverCommission(val, row)"
													@blur="onSetGoodsInfo"
												/>
											</template>
										</el-table-column>
										<el-table-column label="金牌佣金" align="center" prop="gold_commission">
											<template #default="{ row }">
												<el-input
													v-model="row.gold_commission"
													placeholder="金牌佣金"
													@input="(val: string) => onVerifiyNumberIntegerGoldCommission(val, row)"
													@blur="onSetGoodsInfo"
												/>
											</template>
										</el-table-column>
										<el-table-column label="积分" align="center" prop="integral">
											<template #default="{ row }">
												<el-input
													v-model="row.integral"
													placeholder="积分"
													@input="(val: string) => onVerifiyNumberIntegerIntegral(val, row)"
													@blur="onSetGoodsInfo"
												/>
											</template>
										</el-table-column>
										<el-table-column label="总库存" align="center" prop="stock">
											<template #default="{ row }">
												<el-input
													v-if="state.dialog.type === 'add'"
													v-model="row.stock"
													placeholder="总库存"
													@input="(val: string) => onVerifiyNumberIntegerStock(val, row)"
													@blur="onSetGoodsInfo"
												/>
												<span v-else>{{ row.stock }}</span>
											</template>
										</el-table-column>
										<el-table-column label="售价" align="center" prop="price" :formatter="formatterPrice">
											<template #header>
												售价
												<el-tooltip effect="dark" content="售价 = 成本价 + 平台服务费 + 铜牌佣金 + 银牌佣金 + 金牌佣金" placement="top">
													<el-icon>
														<ele-InfoFilled />
													</el-icon>
												</el-tooltip>
											</template>
										</el-table-column>
										<!-- <template v-if="state.dialog.type === 'view'">
											<el-table-column label="剩余库存" align="center" prop="stock_sy" />
											<el-table-column label="真实销量" align="center" prop="real_sales" :formatter="formatterRealSales" />
										</template> -->
									</el-table>
								</el-form-item>
							</el-col>
						</el-row>
						<template v-else>
							<el-row :gutter="20">
								<el-col :span="19">
									<span style="color: red; line-height: 32px"> 注：规格图片尺寸160*160 </span>
								</el-col>
								<el-col :span="5" style="text-align: right">
									<el-button type="primary" @click="onAddSpecs"> 添加新规格 </el-button>
									<el-button type="success" @click="onAtOnceGenerate"> 立即生成 </el-button>
								</el-col>
							</el-row>
							<el-table :data="state.specifications.specifications" border class="mb20">
								<el-table-column label="规格名" prop="name" align="center" width="130px">
									<template #default="{ row }">
										<el-input v-model="row.name" @blur="onSetGoodsInfo" placeholder="规格名" />
									</template>
								</el-table-column>
								<el-table-column label="规格值" align="center">
									<template #default="{ row, $index }">
										<template v-if="$index">
											<el-tag v-for="(item, index) in row.leaf" :key="index" closable hit @close="onDeleteSpecValue($index, index)" class="mr10">
												{{ item.name }}
											</el-tag>
										</template>
										<template v-else>
											<div v-for="(item, index) in row.leaf" :key="index" class="img_sku-item mr10">
												<el-tag closable hit @close="onDeleteSpecValue($index, index)">{{ item.name }} </el-tag>
												<ImageUploadCOS v-model="item.icon" :is-show-tip="false" is-other class="icon-imageUploadCOS" />
											</div>
										</template>
									</template>
								</el-table-column>
								<el-table-column label="操作" align="center" width="300">
									<template #default="{ row, $index }">
										<el-row :gutter="20">
											<el-col :span="18">
												<el-input v-model="row.attribute" @keyup.enter="onAddSpecValue($index)" placeholder="新增一个规格属性">
													<template #append>
														<el-button @click="onAddSpecValue($index)">添加</el-button>
													</template>
												</el-input>
											</el-col>
											<el-col :span="6">
												<el-popconfirm v-if="$index" title="您确定删除该数据？此操作不可撤回" @confirm="onDeleteSpecs($index)" width="180px">
													<template #reference>
														<el-button type="danger">删除 </el-button>
													</template>
												</el-popconfirm>
											</el-col>
										</el-row>
									</template>
								</el-table-column>
							</el-table>
							<template v-if="state.specifications.specifications_val.length">
								<el-row class="mb20" :gutter="20">
									<el-col :span="24">
										<el-form-item label="批量设置">
											<el-table :data="state.batchSettingList" border>
												<el-table-column label="原价" align="center" prop="original_price">
													<template #default="{ row }">
														<el-input
															v-model="row.original_price"
															placeholder="原价"
															@input="(val: string) => onVerifiyNumberIntegerOriginalPrice(val, row)"
														/>
													</template>
												</el-table-column>
												<el-table-column label="成本价" align="center" prop="cost_price">
													<template #default="{ row }">
														<el-input
															v-model="row.cost_price"
															placeholder="成本价"
															@input="(val: string) => onVerifiyNumberIntegerCostPrice(val, row)"
														/>
													</template>
												</el-table-column>
												<el-table-column label="平台服务费" align="center" prop="service_price">
													<template #default="{ row }">
														<el-input
															v-model="row.service_price"
															placeholder="平台服务费"
															@input="(val: string) => onVerifiyNumberIntegerServicePrice(val, row)"
															@blur="onServicePriceBlur1(row)"
														/>
													</template>
												</el-table-column>
												<el-table-column label="铜牌佣金" align="center" prop="bronze_commission">
													<template #default="{ row }">
														<el-input
															v-model="row.bronze_commission"
															placeholder="铜牌佣金"
															@input="(val: string) => onVerifiyNumberIntegerBronzeCommission(val, row)"
														/>
													</template>
												</el-table-column>
												<el-table-column label="银牌佣金" align="center" prop="silver_commission">
													<template #default="{ row }">
														<el-input
															v-model="row.silver_commission"
															placeholder="银牌佣金"
															@input="(val: string) => onVerifiyNumberIntegerSilverCommission(val, row)"
														/>
													</template>
												</el-table-column>
												<el-table-column label="金牌佣金" align="center" prop="gold_commission">
													<template #default="{ row }">
														<el-input
															v-model="row.gold_commission"
															placeholder="金牌佣金"
															@input="(val: string) => onVerifiyNumberIntegerGoldCommission(val, row)"
														/>
													</template>
												</el-table-column>
												<el-table-column label="积分" align="center" prop="integral">
													<template #default="{ row }">
														<el-input v-model="row.integral" placeholder="积分" @input="(val: string) => onVerifiyNumberIntegerIntegral(val, row)" />
													</template>
												</el-table-column>
												<el-table-column v-if="state.dialog.type === 'add'" label="总库存" align="center" prop="stock">
													<template #default="{ row }">
														<el-input v-model="row.stock" placeholder="总库存" @input="(val: string) => onVerifiyNumberIntegerStock(val, row)" />
													</template>
												</el-table-column>
												<el-table-column label="操作" align="center" prop="operation" fixed="right">
													<template #default="{ row }">
														<el-button type="primary" link @click="onBatchSetting(row)">批量设置</el-button>
														<el-button type="primary" link @click="onClear"> 清空 </el-button>
													</template>
												</el-table-column>
											</el-table>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="24">
										<el-form-item label="规格属性">
											<el-table :data="state.specifications.specifications_val" border>
												<el-table-column v-if="state.dialog.type === 'view'" label="规格ID" align="center" prop="id" />
												<el-table-column label="图片" align="center">
													<template #default="{ row }">
														<el-avatar v-if="row.icon" :src="row.icon" shape="square" />
													</template>
												</el-table-column>
												<el-table-column label="规格名称" align="center">
													<template #default="{ row }">
														{{ row.skus.map((item: any) => item.k).join('_') }}
													</template>
												</el-table-column>
												<el-table-column label="规格值" align="center">
													<template #default="{ row }">
														{{ row.skus.map((item: any) => item.v).join('_') }}
													</template>
												</el-table-column>
												<el-table-column label="原价" align="center" prop="original_price">
													<template #default="{ row }">
														<el-input
															v-model="row.original_price"
															placeholder="原价"
															@input="(val: string) => onVerifiyNumberIntegerOriginalPrice(val, row)"
															@blur="onSetGoodsInfo"
														/>
													</template>
												</el-table-column>
												<el-table-column label="成本价" align="center" prop="cost_price">
													<template #default="{ row }">
														<el-input
															v-model="row.cost_price"
															placeholder="成本价"
															@input="(val: string) => onVerifiyNumberIntegerCostPrice(val, row)"
															@blur="onSetGoodsInfo"
														/>
													</template>
												</el-table-column>
												<el-table-column label="平台服务费" align="center" prop="service_price">
													<template #default="{ row, $index }">
														<el-input
															v-model="row.service_price"
															placeholder="平台服务费"
															@input="(val: string) => onVerifiyNumberIntegerServicePrice(val, row)"
															@blur="onServicePriceBlur(row, $index)"
														/>
													</template>
												</el-table-column>
												<el-table-column label="铜牌佣金" align="center" prop="bronze_commission">
													<template #default="{ row }">
														<el-input
															v-model="row.bronze_commission"
															placeholder="铜牌佣金"
															@input="(val: string) => onVerifiyNumberIntegerBronzeCommission(val, row)"
															@blur="onSetGoodsInfo"
														/>
													</template>
												</el-table-column>
												<el-table-column label="银牌佣金" align="center" prop="silver_commission">
													<template #default="{ row }">
														<el-input
															v-model="row.silver_commission"
															placeholder="银牌佣金"
															@input="(val: string) => onVerifiyNumberIntegerSilverCommission(val, row)"
															@blur="onSetGoodsInfo"
														/>
													</template>
												</el-table-column>
												<el-table-column label="金牌佣金" align="center" prop="gold_commission">
													<template #default="{ row }">
														<el-input
															v-model="row.gold_commission"
															placeholder="金牌佣金"
															@input="(val: string) => onVerifiyNumberIntegerGoldCommission(val, row)"
															@blur="onSetGoodsInfo"
														/>
													</template>
												</el-table-column>
												<el-table-column label="积分" align="center" prop="integral">
													<template #default="{ row }">
														<el-input
															v-model="row.integral"
															placeholder="积分"
															@input="(val: string) => onVerifiyNumberIntegerIntegral(val, row)"
															@blur="onSetGoodsInfo"
														/>
													</template>
												</el-table-column>
												<el-table-column label="总库存" align="center" prop="stock">
													<template #default="{ row }">
														<el-input
															v-if="state.dialog.type === 'add'"
															v-model="row.stock"
															placeholder="总库存"
															@input="(val: string) => onVerifiyNumberIntegerStock(val, row)"
															@blur="onSetGoodsInfo"
														/>
														<span v-else>{{ row.stock }}</span>
													</template>
												</el-table-column>
												<el-table-column label="售价" align="center" prop="price" :formatter="formatterPrice">
													<template #header>
														售价
														<el-tooltip effect="dark" content="售价 = 成本价 + 平台服务费 + 铜牌佣金 + 银牌佣金 + 金牌佣金" placement="top">
															<el-icon>
																<ele-InfoFilled />
															</el-icon>
														</el-tooltip>
													</template>
												</el-table-column>
												<!-- <template v-if="state.dialog.type === 'view'">
													<el-table-column label="剩余库存" align="center" prop="stock_sy" />
													<el-table-column label="真实销量" align="center" prop="real_sales" :formatter="formatterRealSales" />
												</template> -->
											</el-table>
										</el-form-item>
									</el-col>
								</el-row>
							</template>
						</template>
					</el-tab-pane>
					<el-tab-pane label="物流/售后设置" :name="4">
						<el-row class="mb20" :gutter="20">
							<el-col :span="12">
								<el-form-item label="物流方式" prop="template_id">
									<el-select
										v-model="state.ruleForm.template_id"
										clearable
										placeholder="请输入关键字/选择物流方式"
										filterable
										remote
										:remote-method="templateIdRemoteMethod"
										remote-show-suffix
										:loading="state.templateIdSelect.loading"
										@focus="onTemplateIdFocus"
										@blur="onSetGoodsInfo"
									>
										<el-option v-for="item in state.templateIdSelect.options" :key="item.id" :label="item.name" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="运费计算方式" prop="billing_method">
									<el-radio-group v-model="state.ruleForm.billing_method" @change="onSetGoodsInfo">
										<el-radio :value="2">多商品记一次运费</el-radio>
										<el-radio :value="1">多商品记多次运费</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="支持售后" prop="is_after">
									<el-radio-group v-model="state.ruleForm.is_after" @change="onSetGoodsInfo">
										<el-radio :value="1">是</el-radio>
										<el-radio :value="2">否</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col v-if="state.ruleForm.is_after === 1" :span="12">
								<el-form-item label="退货地址" prop="supplier_address_id">
									<el-select
										v-model="state.ruleForm.supplier_address_id"
										clearable
										placeholder="请输入关键字/选择退货地址"
										filterable
										remote
										:remote-method="supplierAddressIdRemoteMethod"
										remote-show-suffix
										:loading="state.supplierAddressIdSelect.loading"
										@focus="onSupplierAddressIdFocus"
										@blur="onSetGoodsInfo"
									>
										<el-option v-for="item in state.supplierAddressIdSelect.options" :key="item.id" :label="item.info" :value="item.id" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-tab-pane>
				</el-tabs>
			</el-form>
			<template v-if="state.dialog.type !== 'view'" #footer>
				<el-button v-if="state.ruleForm.tabs_type > 1" @click="onLastStep" size="default">上一步</el-button>
				<el-button type="primary" @click="onSubmit" :loading="state.dialog.submitLoading" size="default">
					{{ state.ruleForm.tabs_type === 4 ? '提 交' : '下一步' }}
				</el-button>
			</template>
		</el-dialog>
		<EditVirtualSalesDialog ref="editVirtualSalesDialogRef" />
	</div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, nextTick, reactive, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';

import { goodsApi, systemApi } from '/@/api';
import { useBasicInfo } from '/@/stores/basicInfo';
import { verifiyNumberInteger } from '/@/utils/toolsValidate';
import { floatAdd, floatMultiply } from '/@/utils/dictionary';
import { Local } from '/@/utils/storage';

const EditVirtualSalesDialog = defineAsyncComponent(() => import('./editVirtualSalesDialog.vue'));

let callback: Function = () => {};
const storesBasicInfo = useBasicInfo();
const { goodsInfo } = storeToRefs(storesBasicInfo);
const GoodsApi = goodsApi();
const SystemApi = systemApi();
// 定义变量内容
const state = reactive({
	loading1: true,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
		loading: true,
	},
	ruleForm: {
		goods_id: '',
		tabs_type: 1,
		title: '',
		goods_class_id: '',
		brand_id: '',
		supplier_id: '',
		type: 1,
		grade: '',
		descri: '',
		virtual_sales: '',
		display_order: '',
		thumb: '',
		thumb_en: '',
		thumb_lo: '',
		thumb_video: '',
		thumb_video_en: '',
		thumb_video_lo: '',
		images: '',
		images_en: '',
		images_lo: '',
		details: '',
		details_en: '',
		details_lo: '',
		template_id: '',
		is_batch_setting: 1,
		billing_method: 2,
		is_after: 1,
		supplier_address_id: '',
		is_specs: 1,
		status: 1,
	},
	rules: {
		title: [{ required: true, message: '商品名称不能为空', trigger: ['blur'] }],
		goods_class_id: [{ required: true, message: '商品分类不能为空', trigger: ['blur', 'change'] }],
		brand_id: [{ required: true, message: '商品品牌不能为空', trigger: ['blur', 'change'] }],
		supplier_id: [{ required: true, message: '关联供应商不能为空', trigger: ['blur', 'change'] }],
		grade: [{ required: true, message: '礼包等级不能为空', trigger: ['blur'] }],
		descri: [{ required: true, message: '商品描述不能为空', trigger: ['blur'] }],
		thumb: [{ required: true, message: '商品主图不能为空', trigger: ['blur', 'change'] }],
		images: [{ required: true, message: '商品轮播图不能为空', trigger: ['blur', 'change'] }],
		details: [{ required: true, message: '商品详情图不能为空', trigger: ['blur', 'change'] }],
		template_id: [{ required: true, message: '物流方式不能为空', trigger: ['blur', 'change'] }],
		supplier_address_id: [{ required: true, message: '退货地址不能为空', trigger: ['blur', 'change'] }],
	},
	batchSettingList: [
		{
			original_price: '',
			cost_price: '',
			service_price: '',
			bronze_commission: '',
			silver_commission: '',
			gold_commission: '',
			integral: '',
			stock: '',
		},
	],
	specifications_val: [
		{
			original_price: '',
			cost_price: '',
			service_price: '',
			bronze_commission: '',
			silver_commission: '',
			gold_commission: '',
			integral: '',
			stock: '',
			skus: [{ k: '', k_id: 1, v: '', v_id: 11 }],
			icon: '',
		},
	],
	specifications: {
		specifications: [] as any,
		specifications_val: [] as any,
	},
	supplierIdSelect: {
		loading: false,
		options: [] as any,
	},
	goodsClassIdSelect: {
		loading: false,
		options: [] as any,
	},
	brandIdSelect: {
		loading: false,
		options: [] as any,
	},
	templateIdSelect: {
		loading: false,
		options: [] as any,
	},
	supplierAddressIdSelect: {
		loading: false,
		options: [] as any,
	},
	gradeOptions: [
		{
			value: 1,
			label: '铜牌会员礼包',
		},
		{
			value: 2,
			label: '银牌会员礼包',
		},
		{
			value: 3,
			label: '金牌会员礼包',
		},
	],
	commissionForm: {
		one_service_rate: '',
		two_service_rate: '',
		three_service_rate: '',
	},
	defaultIntegral: '',
});
const formRef = ref();
const editVirtualSalesDialogRef = ref();

watch(
	() => state.ruleForm.thumb,
	(e) => e && onSetGoodsInfo()
);
watch(
	() => state.ruleForm.thumb_video,
	(e) => e && onSetGoodsInfo()
);
watch(
	() => state.ruleForm.images,
	(e) => e && onSetGoodsInfo()
);
watch(
	() => state.ruleForm.details,
	(e) => e && onSetGoodsInfo()
);

/********** 触发事件 **********/
// 存储商品草稿
const onSetGoodsInfo = () => {
	if (state.dialog.type === 'add') {
		storesBasicInfo.setGoodsInfo({
			ruleForm: {
				...state.ruleForm,
				tabs_type: 1,
			},
			specifications_val: state.ruleForm.is_specs === 1 ? state.specifications_val : [],
			specifications: state.ruleForm.is_specs === 1 ? {} : state.specifications,
			goodsClassIdOptions: state.goodsClassIdSelect.options,
			brandIdOptions: state.brandIdSelect.options,
			supplierIdOptions: state.supplierIdSelect.options,
			templateIdOptions: state.templateIdSelect.options,
			supplierAddressIdOptions: state.supplierAddressIdSelect.options,
		});
	}
};
// 关联商品分类获取焦点
const onGoodsClassIdFocus = () => {
	if (state.ruleForm.goods_class_id) return;
	_goodsSelectClass({ pageNum: 1, pageSize: 10 });
};
// 关联品牌获取焦点
const onBrandIdFocus = () => {
	if (state.ruleForm.brand_id) return;
	_goodsSelectGoodsBrand({ pageNum: 1, pageSize: 10 });
};
// 关联供应商获取焦点
const onSupplierIdFocus = () => {
	if (state.ruleForm.supplier_id) return;
	_goodsSelectSupplier({ pageNum: 1, pageSize: 10 });
};
const onSupplierIdChange = () => {
	state.ruleForm.supplier_address_id = '';
	state.supplierAddressIdSelect.options = [];
};
// 虚拟销量过滤
const onVerifiyNumberIntegerVirtualSales = (val: string) => {
	state.ruleForm.virtual_sales = verifiyNumberInteger(val);
};
// 修改虚拟销量
const onEditVirtualSales = () => {
	editVirtualSalesDialogRef.value.openDialog(
		{
			goods_id: state.ruleForm.goods_id,
			title: state.ruleForm.title,
			virtual_sales: state.ruleForm.virtual_sales,
		},
		(res: any) => {
			state.ruleForm.virtual_sales = res;
		}
	);
};
// 排序过滤
const onVerifiyNumberIntegerDisplayOrder = (val: string) => {
	state.ruleForm.display_order = verifiyNumberInteger(val);
};
// 物流方式获取焦点
const onTemplateIdFocus = () => {
	if (state.ruleForm.template_id) return;
	_goodsSelectFreightTemplate({ pageNum: 1, pageSize: 10 });
};
// 退货地址获取焦点
const onSupplierAddressIdFocus = () => {
	if (!state.ruleForm.supplier_id) return ElMessage.warning('请先选择供应商');
	if (state.ruleForm.supplier_address_id) return;
	_goodsSelectSupplierAddress({ pageNum: 1, pageSize: 10, supplier_id: state.ruleForm.supplier_id });
};
// 原价过滤
const onVerifiyNumberIntegerOriginalPrice = (val: string, row: any) => {
	row.original_price = verifiyNumberInteger(val);
};
// 成本价过滤
const onVerifiyNumberIntegerCostPrice = (val: string, row: any) => {
	row.cost_price = verifiyNumberInteger(val);
};
// 平台服务费过滤
const onVerifiyNumberIntegerServicePrice = (val: string, row: any) => {
	row.service_price = verifiyNumberInteger(val);
};
// 平台服务费失去焦点
const onServicePriceBlur = (row: any, rowIndex: number) => {
	if (state.ruleForm.is_batch_setting) {
		row = {
			...row,
			bronze_commission: parseInt(floatMultiply(row.service_price, state.commissionForm.one_service_rate)),
			silver_commission: parseInt(floatMultiply(row.service_price, state.commissionForm.two_service_rate)),
			gold_commission: parseInt(floatMultiply(row.service_price, state.commissionForm.three_service_rate)),
		};
		if (state.ruleForm.is_specs === 1) {
			state.specifications_val = state.specifications_val.map((item: any, index: number) => {
				return rowIndex === index ? row : item;
			});
		} else {
			state.specifications.specifications_val = state.specifications.specifications_val.map((item: any, index: number) => {
				return rowIndex === index ? row : item;
			});
		}
		onSetGoodsInfo();
	}
};
// 批量平台服务费失去焦点
const onServicePriceBlur1 = (row: any) => {
	if (state.ruleForm.is_batch_setting) {
		row = {
			...row,
			bronze_commission: parseInt(floatMultiply(row.service_price, state.commissionForm.one_service_rate)),
			silver_commission: parseInt(floatMultiply(row.service_price, state.commissionForm.two_service_rate)),
			gold_commission: parseInt(floatMultiply(row.service_price, state.commissionForm.three_service_rate)),
		};
		state.batchSettingList = [row];
	}
};
// 铜牌佣金
const onVerifiyNumberIntegerBronzeCommission = (val: string, row: any) => {
	row.bronze_commission = verifiyNumberInteger(val);
};
// 银牌佣金
const onVerifiyNumberIntegerSilverCommission = (val: string, row: any) => {
	row.silver_commission = verifiyNumberInteger(val);
};
// 金牌佣金
const onVerifiyNumberIntegerGoldCommission = (val: string, row: any) => {
	row.gold_commission = verifiyNumberInteger(val);
};
// 积分过滤
const onVerifiyNumberIntegerIntegral = (val: string, row: any) => {
	row.integral = verifiyNumberInteger(val);
};
// 总库存过滤
const onVerifiyNumberIntegerStock = (val: string, row: any) => {
	row.stock = verifiyNumberInteger(val);
};
// 添加新规格
const onAddSpecs = () => {
	const specifications = state.specifications.specifications;
	if (specifications.length === 3) return ElMessage.warning('最多三个规格');
	if (!specifications.length) {
		state.specifications.specifications.push({
			id: 1,
			attribute: '',
			name: '',
			leaf: [],
		});
		return;
	}
	if (!specifications[specifications.length - 1].name || !specifications[specifications.length - 1].leaf.length)
		return ElMessage.warning('请完善已有规格');
	state.specifications.specifications.push({
		id: Number(specifications[specifications.length - 1].id) + 1,
		attribute: '',
		name: '',
		leaf: [],
	});
};
// 删除规格
const onDeleteSpecs = (index: number) => {
	state.specifications.specifications.splice(index, 1);
	onSetGoodsInfo();
};
// 添加规格值
const onAddSpecValue = (index: number) => {
	const specifications = state.specifications.specifications;
	if (!specifications[index].name) {
		ElMessage.warning('请输入规格名');
		return true;
	}
	specifications[index].attribute = specifications[index].attribute.trim();
	if (specifications[index].attribute) {
		if (!specifications[index].attribute.includes('_')) {
			let leaf = specifications[index].leaf.filter((item: any) => item.name == specifications[index].attribute);
			if (!leaf.length) {
				if (specifications[index].leaf.length) {
					specifications[index].leaf.push({
						id: Number(specifications[index].leaf[specifications[index].leaf.length - 1].id) + 1,
						name: specifications[index].attribute,
						icon: '',
					});
				} else {
					specifications[index].leaf.push({
						id: Number(String(specifications[index].id) + '1'),
						name: specifications[index].attribute,
						icon: '',
					});
				}
			} else ElMessage.warning('规格里不允许出现相同的规格值');
		} else ElMessage.warning('规格里不允许出现「 _ 」字符，请检查后重新添加');
	}
	state.specifications.specifications = specifications;
	onSetGoodsInfo();
};
// 删除规格值
const onDeleteSpecValue = (index1: number, index: number) => {
	if (state.specifications.specifications[index1].leaf.length < 2) return ElMessage.warning('至少保留一个属性');
	state.specifications.specifications[index1].leaf.splice(index, 1);
	onSetGoodsInfo();
};
// 立即生成
const onAtOnceGenerate = () => {
	const specifications = state.specifications.specifications;
	const findIndexLeaf = specifications.map((item: any) => item.leaf.length).findIndex((item: number) => !item);
	if (!specifications.length) return ElMessage.warning('至少添加一个规格');
	if (findIndexLeaf > -1) return ElMessage.warning('请完善规格值');
	const findIndexIcon = specifications[0].leaf.map((item: any) => item.icon).findIndex((item: number) => !item);
	if (findIndexIcon > -1) return ElMessage.warning('请完善规格图片');
	combinationAttribute();
};
// 批量设置
const onBatchSetting = (row: any) => {
	let specifications_val = state.specifications.specifications_val.map((item: any) => {
		return {
			...item,
			...row,
		};
	});
	state.specifications.specifications_val = specifications_val;
	onSetGoodsInfo();
};
// 清空
const onClear = () => {
	state.batchSettingList = [
		{
			original_price: '',
			cost_price: '',
			service_price: '',
			bronze_commission: '',
			silver_commission: '',
			gold_commission: '',
			integral: '',
			stock: '',
		},
	];
};
// 取消
const onCancel = () => {
	state.dialog = {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
		loading: true,
	};
};
// 上一步
const onLastStep = () => {
	state.ruleForm.tabs_type--;
};
// 提交
const onSubmit = () => {
	if (state.ruleForm.tabs_type === 4) {
		formRef.value.validate((valid: boolean) => {
			if (!valid) {
				const ruleForm = state.ruleForm;
				if (
					!ruleForm.title ||
					!ruleForm.goods_class_id ||
					!ruleForm.brand_id ||
					!ruleForm.supplier_id ||
					!ruleForm.descri ||
					(ruleForm.type === 2 && !ruleForm.grade)
				)
					return ElMessage.warning('「基本信息」必填项不能为空');
				if (!ruleForm.thumb || !ruleForm.images || !ruleForm.details) return ElMessage.warning('「图片信息」必填项不能为空');
				if (!ruleForm.template_id || (ruleForm.is_after === 1 && !ruleForm.supplier_address_id))
					return ElMessage.warning('「物流/售后设置」必填项不能为空');
			}
			let specifications_val: any = [];
			if (state.ruleForm.is_specs === 1) {
				specifications_val = state.specifications_val;
			} else {
				specifications_val = state.specifications.specifications_val;
			}
			const findIndexSkusK = specifications_val.findIndex((item: any) => item.skus[0].k === '');
			const findIndexSkusV = specifications_val.findIndex((item: any) => item.skus[0].v === '');
			const findIndexOriginalPrice = specifications_val.findIndex((item: any) => !Number(item.original_price));
			const findIndexCostPrice = specifications_val.findIndex((item: any) => !Number(item.cost_price));
			const findIndexServicePrice = specifications_val.findIndex((item: any) => item.service_price === '');
			const findIndexBronzeCommission = specifications_val.findIndex((item: any) => item.bronze_commission === '');
			const findIndexSilverCommission = specifications_val.findIndex((item: any) => item.silver_commission === '');
			const findIndexGoldCommission = specifications_val.findIndex((item: any) => item.gold_commission === '');
			const findIndexStock = specifications_val.findIndex((item: any) => item.stock === '');
			if (state.ruleForm.is_specs === 2) {
				const specificationsValLength = combinationAttribute1().length;
				if (specificationsValLength !== specifications_val.length) return ElMessage.warning('修改了规格需点击「立即生成」重新生成规格哦');
			} else {
				if (findIndexSkusK > -1) return ElMessage.warning('规格属性中的「规格名称」不能为空');
				if (findIndexSkusV > -1) return ElMessage.warning('规格属性中的「规格值」不能为空');
			}
			if (findIndexOriginalPrice > -1) return ElMessage.warning('规格属性中的「原价」不能为空/‘0’');
			if (findIndexCostPrice > -1) return ElMessage.warning('规格属性中的「成本价」不能为空/‘0’');
			if (findIndexServicePrice > -1) return ElMessage.warning('规格属性中的「平台服务费」不能为空');
			if (findIndexBronzeCommission > -1) return ElMessage.warning('规格属性中的「铜牌佣金」不能为空');
			if (findIndexSilverCommission > -1) return ElMessage.warning('规格属性中的「银牌佣金」不能为空');
			if (findIndexGoldCommission > -1) return ElMessage.warning('规格属性中的「金牌佣金」不能为空');
			if (state.dialog.type === 'add' && findIndexStock > -1) return ElMessage.warning('规格属性中的「库存」不能为空');
			if (!specifications_val.length) return ElMessage.warning('请点击「立即生成」并完善规格属性');
			let specifications = state.specifications.specifications.map((item: any, index: number) => {
				let leaf = item.leaf.map((leaf_item: any) => {
					return {
						...leaf_item,
						icon: index ? '' : leaf_item.icon,
					};
				});
				return {
					...item,
					leaf,
				};
			});
			state.dialog.submitLoading = true;
			if (state.ruleForm.is_specs === 1) {
				specifications = [
					{
						name: specifications_val[0].skus[0].k,
						id: specifications_val[0].skus[0].k_id,
						leaf: [
							{
								id: specifications_val[0].skus[0].v_id,
								name: specifications_val[0].skus[0].v,
								icon: specifications_val[0].icon,
							},
						],
					},
				];
			} else {
				specifications = state.specifications.specifications.map((item: any, index: number) => {
					let leaf = item.leaf.map((leaf_item: any) => {
						return {
							...leaf_item,
							icon: index ? '' : leaf_item.icon,
						};
					});
					return {
						...item,
						leaf,
					};
				});
			}
			const params = {
				...state.ruleForm,
				thumb: state.ruleForm.thumb,
				thumb_lo: state.ruleForm.thumb_lo || state.ruleForm.thumb,
				thumb_video_lo: state.ruleForm.thumb_video_lo || state.ruleForm.thumb_video,
				images_lo: state.ruleForm.images_lo || state.ruleForm.images,
				details_lo: state.ruleForm.details_lo || state.ruleForm.details,
				thumb_en: state.ruleForm.thumb_en || state.ruleForm.thumb,
				thumb_video_en: state.ruleForm.thumb_video_en || state.ruleForm.thumb_video,
				images_en: state.ruleForm.images_en || state.ruleForm.images,
				details_en: state.ruleForm.details_en || state.ruleForm.details,
				goods_class_id: state.ruleForm.goods_class_id,
				specifications: JSON.stringify({ specifications, specifications_val }),
			};
			console.log('params', params);
			if (state.dialog.type === 'edit') {
				const goodsSpecsItem = specifications.map((item: any) => {
					let leaf_str = item.leaf.map((item1: any) => item1.id).join(',');
					return leaf_str;
				});
				const goods_specs_str = specifications.map((item: any) => item.id).join(',');
				const goods_specs_item_str = goodsSpecsItem.map((item: any) => item).join(',');
				const goods_option_str = specifications_val.map((item: any) => item.id).join(',');
				let params1 = {
					goods_id: state.ruleForm.goods_id,
					specifications: JSON.stringify({ specifications, specifications_val }),
					goods_specs_item_str,
					goods_specs_str,
					goods_option_str,
				};
				_goodsEdit(params, params1);
			} else {
				_goodsAdd(params);
			}
		});
		return;
	}
	state.ruleForm.tabs_type++;
};

/********** 方法事件 **********/
// 打开
const openDialog = (data: any, row: any, fn: Function) => {
	if (Local.get('goodsInfo')) {
		storesBasicInfo.setGoodsInfo(Local.get('goodsInfo'));
	}
	state.dialog = {
		isShowDialog: true,
		type: data.type,
		title: data.title,
		submitLoading: false,
		loading: false,
	};
	state.specifications_val = [
		{
			original_price: '',
			cost_price: '',
			service_price: '',
			bronze_commission: '',
			silver_commission: '',
			gold_commission: '',
			integral: '',
			stock: '',
			skus: [{ k: '', k_id: 1, v: '', v_id: 11 }],
			icon: '',
		},
	];
	state.batchSettingList = [
		{
			original_price: '',
			cost_price: '',
			service_price: '',
			bronze_commission: '',
			silver_commission: '',
			gold_commission: '',
			integral: '',
			stock: '',
		},
	];
	state.specifications = {
		specifications: [],
		specifications_val: [],
	};
	callback = fn;
	_configSystemSelect({ identification: 'commission_config' });
	nextTick(() => {
		formRef.value.resetFields();
		state.ruleForm.tabs_type = 1;
		state.ruleForm.is_batch_setting = 1;
		if (state.dialog.type === 'add') {
			const info = goodsInfo.value;
			if (Object.keys(info).length) {
				state.ruleForm = info.ruleForm;
				if (state.ruleForm.is_specs === 1) {
					state.specifications_val = info.specifications_val;
				} else {
					state.specifications = info.specifications;
				}
				state.goodsClassIdSelect.options = info.goodsClassIdOptions;
				state.brandIdSelect.options = info.brandIdOptions;
				state.supplierIdSelect.options = info.supplierIdOptions;
				state.templateIdSelect.options = info.templateIdOptions;
				state.supplierAddressIdSelect.options = info.supplierAddressIdOptions;
			}
			_configSystemSelect({ identification: 'integral_config' });
		}
		if (state.dialog.type !== 'add') {
			state.dialog.loading = true;
			_goodsSelect({ goods_id: row.id });
		}
	});
};
// 关联供应商搜索选择
const supplierIdRemoteMethod = (query: string) => {
	if (!query) return;
	_goodsSelectSupplier({ pageNum: 1, pageSize: 10, title: query });
};
// 关联商品分类搜索选择
const goodsClassIdRemoteMethod = (query: string) => {
	if (!query) return;
	_goodsSelectClass({ pageNum: 1, pageSize: 10, name: query });
};
// 关联品牌搜索选择
const brandIdRemoteMethod = (query: string) => {
	if (!query) return;
	_goodsSelectGoodsBrand({ pageNum: 1, pageSize: 10, name: query });
};
// 物流方式搜索选择
const templateIdRemoteMethod = (query: string) => {
	if (!query) return;
	_goodsSelectFreightTemplate({ pageNum: 1, pageSize: 10, name: query });
};
// 退货地址搜索选择
const supplierAddressIdRemoteMethod = (query: string) => {
	if (!query) return;
	_goodsSelectSupplierAddress({ pageNum: 1, pageSize: 10, name: query, supplier_id: state.ruleForm.supplier_id });
};
// 生成 skuData 数据
const combinationAttribute = () => {
	const specifications1 = state.specifications.specifications;
	const specifications_val1 = state.specifications.specifications_val;
	let specifications = specifications1.map((item: any) => {
		return item.leaf.map((item1: any) => item1.name);
	});
	let specifications_val = calcDescartes(specifications).map((item: any) => {
		let skus: any = [];
		let icon = '';
		specifications1.map((item1: any, index: number) => {
			item1.leaf.map((item2: any) => {
				if (item2.name === item[index]) {
					skus.push({
						k: item1.name,
						k_id: item1.id,
						v: item2.name,
						v_id: item2.id,
					});
				}
			});
		});
		specifications1[0].leaf.map((item1: any) => {
			if (item1.name == item[0]) {
				icon = item1.icon;
			}
		});
		const skusJoin = skus.map((item1: any) => item1.v).join('_');
		const ismerge = specifications_val1.find((item1: any) => item1.skus.map((item1: any) => item1.v).join('_') === skusJoin);
		console.log(skusJoin, ismerge);

		if (ismerge === undefined) {
			return {
				original_price: '',
				cost_price: '',
				service_price: '',
				bronze_commission: '',
				silver_commission: '',
				gold_commission: '',
				integral: state.defaultIntegral,
				stock: '',
				skus: skus,
				icon,
			};
		} else {
			return {
				...ismerge,
				skus: skus,
				icon,
			};
		}
	});
	state.specifications.specifications_val = specifications_val;
	onSetGoodsInfo();
};
// 生成 skuData 数据
const combinationAttribute1 = () => {
	const specifications1 = state.specifications.specifications;
	const specifications_val1 = state.specifications.specifications_val;
	let specifications = specifications1.map((item: any) => {
		return item.leaf.map((item1: any) => item1.name);
	});
	let specifications_val = calcDescartes(specifications).map((item: any) => {
		let skus: any = [];
		let icon = '';
		specifications1.map((item1: any, index: number) => {
			item1.leaf.map((item2: any) => {
				if (item2.name === item[index]) {
					skus.push({
						k: item1.name,
						k_id: item1.id,
						v: item2.name,
						v_id: item2.id,
					});
				}
			});
		});
		specifications1[0].leaf.map((item1: any) => {
			if (item1.name == item[0]) {
				icon = item1.icon;
			}
		});
		const skusJoin = skus.map((item1: any) => item1.v).join('_');
		const ismerge = specifications_val1.find((item1: any) => item1.skus.map((item1: any) => item1.v).join('_') === skusJoin);
		console.log(skusJoin, ismerge);

		if (ismerge === undefined) {
			return {
				original_price: '',
				cost_price: '',
				service_price: '',
				bronze_commission: '',
				silver_commission: '',
				gold_commission: '',
				integral: state.defaultIntegral,
				stock: '',
				skus: skus,
				icon,
			};
		} else {
			return {
				...ismerge,
				skus: skus,
				icon,
			};
		}
	});
	return specifications_val;
};
// 生成sku
const calcDescartes = (array: any) => {
	if (array.length < 2) return array[0].map((item: any) => [item]) || [];
	return Array.prototype.reduce.call(
		array,
		(col: any, set: any) => {
			var res: any = [];
			col.forEach((c: any) => {
				set.forEach((s: any) => {
					res.push(c.concat([s]));
				});
			});
			return res;
		},
		[[]]
	);
};
// 售价字典
const formatterPrice = (row: any) => {
	const price1 = floatAdd(row.cost_price, row.service_price);
	const price2 = floatAdd(price1, row.bronze_commission);
	const price3 = floatAdd(price2, row.silver_commission);
	const price = floatAdd(price3, row.gold_commission);
	return price;
};

/********** 网络请求 **********/
// 添加商品
const _goodsAdd = (params: Object) => {
	GoodsApi.goodsAdd(params)
		.then(() => {
			ElMessage.success('操作成功！');
			storesBasicInfo.removeGoodsInfo();
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};
// 编辑商品
const _goodsEdit = (params: Object, params1: Object) => {
	GoodsApi.goodsEdit(params)
		.then(() => {
			_goodsEditSku(params1);
		})
		.catch(() => (state.dialog.submitLoading = false));
};
// 编辑商品sku
const _goodsEditSku = (params: Object) => {
	GoodsApi.goodsEditSku(params)
		.then(() => {
			ElMessage.success('操作成功！');
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};
// 查询商品详情
const _goodsSelect = (params: Object) => {
	GoodsApi.goodsSelect(params)
		.then((res) => {
			const info: any = res.data.info;
			const specifications = res.data.specifications.specifications;
			const specifications_val = res.data.specifications.specifications_val;
			state.dialog.loading = false;
			state.ruleForm = info;
			state.ruleForm.goods_id = info.id;
			state.ruleForm.tabs_type = 1;
			state.ruleForm.is_batch_setting = 1;
			if (state.ruleForm.is_specs === 1) {
				state.specifications_val = specifications_val;
			} else {
				state.specifications = { specifications, specifications_val };
			}
			state.ruleForm.template_id = info.goods_freight_template.template_id;
			state.goodsClassIdSelect.options = [{ id: info.goods_class_id, name: info.goods_class_name }];
			state.brandIdSelect.options = [{ id: info.brand_id, name: info.brand_name }];
			state.supplierIdSelect.options = [{ id: info.supplier_id, name: info.supplier_name }];
			state.templateIdSelect.options = [{ id: info.goods_freight_template.template_id, name: info.goods_freight_template.template_name }];
			state.supplierAddressIdSelect.options = [{ id: info.supplier_address_id, info: `${info.address_name},${info.address_mobile},${info.address}` }];
		})
		.catch(() => (state.dialog.loading = false));
};
// 选择商品分类
const _goodsSelectClass = (params: Object) => {
	state.goodsClassIdSelect.loading = false;
	GoodsApi.goodsSelectClass(params)
		.then((res) => {
			state.goodsClassIdSelect.options = res.data.list;
		})
		.catch(() => (state.goodsClassIdSelect.loading = false));
};
// 选择供应商
const _goodsSelectSupplier = (params: Object) => {
	state.supplierIdSelect.loading = false;
	GoodsApi.goodsSelectSupplier(params)
		.then((res) => {
			state.supplierIdSelect.options = res.data.list;
		})
		.catch(() => (state.supplierIdSelect.loading = false));
};
// 选择商品品牌
const _goodsSelectGoodsBrand = (params: Object) => {
	state.brandIdSelect.loading = false;
	GoodsApi.goodsSelectGoodsBrand(params)
		.then((res) => {
			state.brandIdSelect.options = res.data.list;
		})
		.catch(() => (state.brandIdSelect.loading = false));
};
// 选择运费模板
const _goodsSelectFreightTemplate = (params: Object) => {
	state.templateIdSelect.loading = false;
	GoodsApi.goodsSelectFreightTemplate(params)
		.then((res) => {
			state.templateIdSelect.options = res.data.list;
		})
		.catch(() => (state.templateIdSelect.loading = false));
};
// 选择供应商退换货地址
const _goodsSelectSupplierAddress = (params: Object) => {
	state.supplierAddressIdSelect.loading = false;
	GoodsApi.goodsSelectSupplierAddress(params)
		.then((res) => {
			state.supplierAddressIdSelect.options = res.data.list.map((item: any) => {
				return {
					...item,
					info: `${item.name},${item.mobile},${item.address}`,
				};
			});
		})
		.catch(() => (state.supplierAddressIdSelect.loading = false));
};
// 单个系统配置信息
const _configSystemSelect = (params: any) => {
	SystemApi.configSystemSelect(params).then((res) => {
		const info = res.data.info;
		if (!Object.keys(info).length) return;
		const list = info.item.list;
		if (params.identification === 'commission_config') {
			state.commissionForm = {
				one_service_rate: list.one_service_rate,
				two_service_rate: list.two_service_rate,
				three_service_rate: list.three_service_rate,
			};
		}
		if (params.identification === 'integral_config') {
			state.defaultIntegral = list.integral;
			state.specifications_val = [
				{
					original_price: '',
					cost_price: '',
					service_price: '',
					bronze_commission: '',
					silver_commission: '',
					gold_commission: '',
					integral: list.integral,
					stock: '',
					skus: [{ k: '', k_id: 1, v: '', v_id: 11 }],
					icon: '',
				},
			];
			state.batchSettingList = [
				{
					original_price: '',
					cost_price: '',
					service_price: '',
					bronze_commission: '',
					silver_commission: '',
					gold_commission: '',
					integral: list.integral,
					stock: '',
				},
			];
			const info = goodsInfo.value;
			if (Object.keys(info).length) {
				if (state.ruleForm.is_specs === 1) {
					state.specifications_val = info.specifications_val;
				} else {
					state.specifications = info.specifications;
				}
			}
		}
	});
};

/********** 方法向父组件暴露 **********/
defineExpose({ openDialog });
</script>

<style lang="scss" scoped>
.dialog-container {
	.img_sku-item {
		display: inline-block;
	}
	:deep(.icon-imageUploadCOS) {
		width: 60px;
		height: 60px;
		margin: auto;

		.fileComputed {
			width: 60px;
			height: 60px;
		}

		.el-upload-list--picture-card {
			width: 60px;
			height: 60px;

			.el-upload--picture-card {
				width: 60px;
				height: 60px;
			}

			.el-upload-list__item {
				width: 60px;
				height: 60px;
				margin: 0;

				.el-upload-list__item-actions {
					.el-upload-list__item-preview {
						display: none;
					}
					.el-upload-list__item-delete {
						margin: 0;
					}
				}
			}
		}
	}
}
</style>
